<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="springboot 二开github blog项目（一） 花了一周的时间摸坑javaweb、springboot，动手写了几个小demo，包括了基础的CRUD，登录注册、session、token、Security等内容以及springboot整合其他框架：druid，mybatis，thymeleaf等；现在继续学要有个案例，学习复刻别人已经写得相对比较完善的代码效果会更加显著。所以选取了gi">
<meta property="og:type" content="article">
<meta property="og:title" content="springboot">
<meta property="og:url" content="http://example.com/2021/03/15/springboot%20%E6%A1%88%E4%BE%8B%E5%AD%A6%E4%B9%A0/index.html">
<meta property="og:site_name" content="yyc&#39;s blog">
<meta property="og:description" content="springboot 二开github blog项目（一） 花了一周的时间摸坑javaweb、springboot，动手写了几个小demo，包括了基础的CRUD，登录注册、session、token、Security等内容以及springboot整合其他框架：druid，mybatis，thymeleaf等；现在继续学要有个案例，学习复刻别人已经写得相对比较完善的代码效果会更加显著。所以选取了gi">
<meta property="og:locale">
<meta property="og:image" content="https://gitee.com/goatyyc/giteep-page-imgs/raw/master/imgs/20210315234244.png">
<meta property="og:image" content="https://gitee.com/goatyyc/giteep-page-imgs/raw/master/imgs/20210315234245.png">
<meta property="og:image" content="https://gitee.com/goatyyc/giteep-page-imgs/raw/master/imgs/20210315234246.png">
<meta property="og:image" content="https://gitee.com/goatyyc/giteep-page-imgs/raw/master/imgs/20210315234247.png">
<meta property="og:image" content="https://gitee.com/goatyyc/giteep-page-imgs/raw/master/imgs/20210315234248.png">
<meta property="og:image" content="https://gitee.com/goatyyc/giteep-page-imgs/raw/master/imgs/20210315234249.png">
<meta property="og:image" content="https://gitee.com/goatyyc/giteep-page-imgs/raw/master/imgs/20210315234250.png">
<meta property="article:published_time" content="2021-03-15T15:38:53.000Z">
<meta property="article:modified_time" content="2021-03-16T06:31:56.863Z">
<meta property="article:author" content="yyc">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/goatyyc/giteep-page-imgs/raw/master/imgs/20210315234244.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://example.com/2021/03/15/springboot 案例学习/"/>





  <title>springboot | yyc's blog</title>
  








<meta name="generator" content="Hexo 5.3.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta custom-logo">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">yyc's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">技术博客</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/03/15/springboot%20%E6%A1%88%E4%BE%8B%E5%AD%A6%E4%B9%A0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="yyc's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">springboot</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2021-03-15T23:38:53+08:00">
                2021-03-15
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/springboot/" itemprop="url" rel="index">
                    <span itemprop="name">springboot</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="springboot-二开github-blog项目（一）"><a href="#springboot-二开github-blog项目（一）" class="headerlink" title="springboot 二开github blog项目（一）"></a>springboot 二开github blog项目（一）</h1><blockquote>
<p>花了一周的时间摸坑javaweb、springboot，动手写了几个小demo，包括了基础的CRUD，登录注册、session、token、Security等内容以及springboot整合其他框架：druid，mybatis，thymeleaf等；现在继续学要有个案例，学习复刻别人已经写得相对比较完善的代码效果会更加显著。所以选取了github上的一个springboot搭建blog项目进行二次开发。</p>
</blockquote>
<a id="more"></a>

<h2 id="一、环境搭建"><a href="#一、环境搭建" class="headerlink" title="一、环境搭建"></a>一、环境搭建</h2><h3 id="1、拉去项目到本地："><a href="#1、拉去项目到本地：" class="headerlink" title="1、拉去项目到本地："></a>1、拉去项目到本地：</h3><blockquote>
<p>地址：<a target="_blank" rel="noopener" href="https://github.com/zhisheng17/blog">https://github.com/zhisheng17/blog</a></p>
</blockquote>
<p>解压到本地后用idea导入为maven项目</p>
<p><img src="https://gitee.com/goatyyc/giteep-page-imgs/raw/master/imgs/20210315234244.png" alt="image-20210315152505292"></p>
<p><img src="https://gitee.com/goatyyc/giteep-page-imgs/raw/master/imgs/20210315234245.png" alt="image-20210315152526613"></p>
<h3 id="2、配置数据库"><a href="#2、配置数据库" class="headerlink" title="2、配置数据库"></a>2、配置数据库</h3><p>远程或者本地的数据库皆可</p>
<p>在navicat中新建lu_tale数据库，执行源文件中的sql即可</p>
<p>修改yaml：</p>
<p><img src="https://gitee.com/goatyyc/giteep-page-imgs/raw/master/imgs/20210315234246.png" alt="image-20210315163315519"></p>
<h3 id="3、本地运行"><a href="#3、本地运行" class="headerlink" title="3、本地运行"></a>3、本地运行</h3><p>在MySiteApplication跑起来，浏览器打开 localhost:8080</p>
<p>成功地跑起来了</p>
<p><img src="https://gitee.com/goatyyc/giteep-page-imgs/raw/master/imgs/20210315234247.png" alt="image-20210315210318533"></p>
<h2 id="二、架构解析"><a href="#二、架构解析" class="headerlink" title="二、架构解析"></a>二、架构解析</h2><p><img src="https://gitee.com/goatyyc/giteep-page-imgs/raw/master/imgs/20210315234248.png" alt="image-20210315210746082"></p>
<p>跟我们常用springboot架构一样：</p>
<h3 id="1、运行逻辑："><a href="#1、运行逻辑：" class="headerlink" title="1、运行逻辑："></a>1、运行逻辑：</h3><p>控制器调用service层，service层编写业务逻辑代码，当涉及到数据库读写时，调用dao层的实体类，与实体类对应的mapper层则用于编写查询、读取的sql语句，最后通过pojo类作为载体传递出去。</p>
<h3 id="2、示例代码："><a href="#2、示例代码：" class="headerlink" title="2、示例代码："></a>2、示例代码：</h3><p>以管理员登陆这一业务，来看这个开源项目的实例：</p>
<h4 id="（1）控制器层"><a href="#（1）控制器层" class="headerlink" title="（1）控制器层"></a>（1）控制器层</h4><p><img src="https://gitee.com/goatyyc/giteep-page-imgs/raw/master/imgs/20210315234249.png" alt="image-20210315213345518"></p>
<p>其中还包含了BaseController和HomeController：</p>
<p>BaseController是一个抽象类，用于编写一些基类方法，让其他控制器继承</p>
<p>简单看了一下这个类，里面编写了一些较为常用的方法，如：获取blog页面需要的公共数据、数组转字符串，而包含登录的控制器AuthController继承了该基类控制器，因此也具备了这些方法。</p>
<p>解析AuthController类的成员方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Api(&quot;登录相关接口&quot;)</span></span><br><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="meta">@RequestMapping(value = &quot;/admin&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AuthController</span> <span class="keyword">extends</span> <span class="title">BaseController</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger LOGGER = LogManager.getLogger(AuthController.class);</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserService userService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> LogService logService;</span><br><span class="line">	<span class="comment">// 路径：admin/login会跳转到登录页面</span></span><br><span class="line">    <span class="meta">@ApiOperation(&quot;跳转登录页&quot;)</span></span><br><span class="line">    <span class="meta">@GetMapping(value = &quot;/login&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">login</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;admin/login&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 登录方法</span></span><br><span class="line">    <span class="meta">@ApiOperation(&quot;登录&quot;)</span></span><br><span class="line">    <span class="meta">@PostMapping(value = &quot;/login&quot;)</span>		<span class="comment">// 用Post方法接收</span></span><br><span class="line">    <span class="meta">@ResponseBody</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> APIResponse <span class="title">toLogin</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        	// 接收的参数</span></span></span><br><span class="line"><span class="function"><span class="params">            HttpServletRequest request,</span></span></span><br><span class="line"><span class="function"><span class="params">            HttpServletResponse response,</span></span></span><br><span class="line"><span class="function"><span class="params">            <span class="meta">@ApiParam(name = &quot;username&quot;, value = &quot;用户名&quot;, required = true)</span></span></span></span><br><span class="line"><span class="function"><span class="params">            <span class="meta">@RequestParam(name = &quot;username&quot;, required = true)</span></span></span></span><br><span class="line"><span class="function"><span class="params">            String username,</span></span></span><br><span class="line"><span class="function"><span class="params">            <span class="meta">@ApiParam(name = &quot;password&quot;, value = &quot;密码&quot;, required = true)</span></span></span></span><br><span class="line"><span class="function"><span class="params">            <span class="meta">@RequestParam(name = &quot;password&quot;, required = true)</span></span></span></span><br><span class="line"><span class="function"><span class="params">            String password,</span></span></span><br><span class="line"><span class="function"><span class="params">            <span class="meta">@ApiParam(name = &quot;remeber_me&quot;, value = &quot;记住我&quot;, required = false)</span></span></span></span><br><span class="line"><span class="function"><span class="params">            <span class="meta">@RequestParam(name = &quot;remeber_me&quot;, required = false)</span></span></span></span><br><span class="line"><span class="function"><span class="params">            String remeber_me</span></span></span><br><span class="line"><span class="function"><span class="params">    )</span></span>&#123;</span><br><span class="line">		<span class="comment">// 获取请求的地址</span></span><br><span class="line">        String ip= IPKit.getIpAddrByRequest(request); <span class="comment">// 获取ip并过滤登录时缓存的bug</span></span><br><span class="line">        Integer error_count = cache.hget(<span class="string">&quot;login_error_count&quot;</span>,ip);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            UserDomain userInfo = userService.login(username, password);</span><br><span class="line">            request.getSession().setAttribute(WebConst.LOGIN_SESSION_KEY, userInfo);</span><br><span class="line">            <span class="keyword">if</span> (StringUtils.isNotBlank(remeber_me)) &#123;</span><br><span class="line">                TaleUtils.setCookie(response, userInfo.getUid());</span><br><span class="line">            &#125;</span><br><span class="line">            logService.addLog(LogActions.LOGIN.getAction(), <span class="keyword">null</span>, request.getRemoteAddr(), userInfo.getUid());</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            LOGGER.error(e.getMessage());</span><br><span class="line">            error_count = <span class="keyword">null</span> == error_count ? <span class="number">1</span> : error_count + <span class="number">1</span>;</span><br><span class="line">            <span class="keyword">if</span> (error_count &gt; <span class="number">3</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> APIResponse.fail(<span class="string">&quot;您输入密码已经错误超过3次，请10分钟后尝试&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            cache.hset(<span class="string">&quot;login_error_count&quot;</span>, ip,error_count, <span class="number">10</span> * <span class="number">60</span>); <span class="comment">// 加入ip的过滤</span></span><br><span class="line">            String msg = <span class="string">&quot;登录失败&quot;</span>;</span><br><span class="line">            <span class="keyword">if</span> (e <span class="keyword">instanceof</span> BusinessException) &#123;</span><br><span class="line">                msg = e.getMessage();</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                LOGGER.error(msg, e);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> APIResponse.fail(msg);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> APIResponse.success();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>


<p>登录控制器出于安全的考虑还设置了一些缓存策略以及ip过滤等，仔细研究一下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">protected</span> MapCache cache = MapCache.single();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 工具类IPKit 获取客户端的id地址</span></span><br><span class="line">String ip= IPKit.getIpAddrByRequest(request); <span class="comment">// 获取ip并过滤登录时缓存的bug</span></span><br><span class="line"><span class="comment">// 记录ip</span></span><br><span class="line">Integer error_count = cache.hget(<span class="string">&quot;login_error_count&quot;</span>,ip);</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    UserDomain userInfo = userService.login(username, password);</span><br><span class="line">    request.getSession().setAttribute(WebConst.LOGIN_SESSION_KEY, userInfo);</span><br><span class="line">    <span class="keyword">if</span> (StringUtils.isNotBlank(remeber_me)) &#123;</span><br><span class="line">        TaleUtils.setCookie(response, userInfo.getUid());</span><br><span class="line">    &#125;</span><br><span class="line">    logService.addLog(LogActions.LOGIN.getAction(), <span class="keyword">null</span>, request.getRemoteAddr(), userInfo.getUid());</span><br><span class="line">&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">    LOGGER.error(e.getMessage());</span><br><span class="line">    error_count = <span class="keyword">null</span> == error_count ? <span class="number">1</span> : error_count + <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">if</span> (error_count &gt; <span class="number">3</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> APIResponse.fail(<span class="string">&quot;您输入密码已经错误超过3次，请10分钟后尝试&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    cache.hset(<span class="string">&quot;login_error_count&quot;</span>, ip,error_count, <span class="number">10</span> * <span class="number">60</span>); <span class="comment">// 加入ip的过滤</span></span><br><span class="line">    String msg = <span class="string">&quot;登录失败&quot;</span>;</span><br><span class="line">    <span class="keyword">if</span> (e <span class="keyword">instanceof</span> BusinessException) &#123;</span><br><span class="line">        msg = e.getMessage();</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        LOGGER.error(msg, e);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> APIResponse.fail(msg);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">return</span> APIResponse.success();</span><br></pre></td></tr></table></figure>
<p>当第一次登录失败（账号密码错误）时，缓存记录ip地址，</p>
<p>此时，error_count==null， 登录失败会抛出异常，缓存加入ip的过滤</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**</span><br><span class="line"> * 设置一个hash缓存并带过期时间</span><br><span class="line"> *</span><br><span class="line"> * @param key     缓存key</span><br><span class="line"> * @param field   缓存field</span><br><span class="line"> * @param value   缓存value</span><br><span class="line"> * @param expired 过期时间，单位为秒</span><br><span class="line"> *&#x2F;</span><br><span class="line">public void hset(String key, String field, Object value, long expired) &#123;</span><br><span class="line">    key &#x3D; key + &quot;:&quot; + field;</span><br><span class="line">    expired &#x3D; expired &gt; 0 ? System.currentTimeMillis() &#x2F; 1000 + expired : expired;</span><br><span class="line">    &#x2F;&#x2F; 实例化一个缓存对象</span><br><span class="line">    CacheObject cacheObject &#x3D; new CacheObject(key, value, expired);</span><br><span class="line">    cachePool.put(key, cacheObject);	&#x2F;&#x2F; 放入缓存池</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>但是这里实际上并没有起到限制作用？只是能够记录ip访问的次数</p>
<p>再看到下面返回的方式：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">return</span> APIResponse.fail(msg);</span><br></pre></td></tr></table></figure>
<p>这个APIResponse 是utils工具类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 返回的参数封装类</span></span><br><span class="line"><span class="comment"> * Created by Donghua.Chen on 2018/4/20.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">APIResponse</span> &lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line"> 	<span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String CODE_SUCCESS = <span class="string">&quot;success&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String CODE_FAIL = <span class="string">&quot;fail&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String code;</span><br><span class="line">    <span class="keyword">private</span> T data;</span><br><span class="line">    <span class="keyword">private</span> String msg;</span><br><span class="line"> 	</span><br><span class="line"> 	<span class="comment">// 构造方法</span></span><br><span class="line">    ...</span><br><span class="line">    <span class="comment">// 成功与失败返回方法</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> APIResponse <span class="title">success</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> APIResponse(CODE_SUCCESS);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> APIResponse <span class="title">success</span><span class="params">(Object data)</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> APIResponse(CODE_SUCCESS, data);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> APIResponse <span class="title">fail</span><span class="params">(String msg)</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> APIResponse(CODE_FAIL, msg);</span><br><span class="line">    &#125;    </span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 其他</span></span><br><span class="line">    ...</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>


<p>解析完缓存ip问题，接下往service层走，看看登录的业务逻辑</p>
<h4 id="（2）service层"><a href="#（2）service层" class="headerlink" title="（2）service层"></a>（2）service层</h4><p>进入UserService层Impl下login的实现方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> UserDomain <span class="title">login</span><span class="params">(String username, String password)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (StringUtils.isBlank(username) || StringUtils.isBlank(password))</span><br><span class="line">        <span class="keyword">throw</span> BusinessException.withErrorCode(ErrorConstant.Auth.USERNAME_PASSWORD_IS_EMPTY);</span><br><span class="line"></span><br><span class="line">    String pwd = TaleUtils.MD5encode(username + password);</span><br><span class="line">    UserDomain user = userDao.getUserInfoByCond(username, pwd);</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">null</span> == user)</span><br><span class="line">        <span class="keyword">throw</span> BusinessException.withErrorCode(ErrorConstant.Auth.USERNAME_PASSWORD_ERROR);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> user;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>业务逻辑：</p>
<ul>
<li><p>判断用户名和密码是否为空，若为空：抛出提示信息</p>
</li>
<li><p>若不为空，对密码进行加密：MD5encode（username+password）</p>
</li>
<li><p>userDao查询用户名密码</p>
</li>
<li><p>判断是否有该用户，若无抛出用户名密码错误，若有返回user对象</p>
</li>
</ul>
<p>这里用到了utils工具类的ErrorConstant接口类的接口信息：</p>
<p><img src="https://gitee.com/goatyyc/giteep-page-imgs/raw/master/imgs/20210315234250.png" alt="image-20210315230629363"></p>
<p>看起代码很规范、优美，复用性也高一些</p>
<p><strong>自定义异常：</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (StringUtils.isBlank(username) || StringUtils.isBlank(password))</span><br><span class="line">            <span class="keyword">throw</span> BusinessException.withErrorCode(ErrorConstant.Auth.USERNAME_PASSWORD_IS_EMPTY);</span><br></pre></td></tr></table></figure>


<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 统一异常类</span></span><br><span class="line"><span class="comment"> * Created by Donghua.Chen on 2018/4/20.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BusinessException</span> <span class="keyword">extends</span> <span class="title">RuntimeException</span> </span>&#123;</span><br><span class="line">     </span><br><span class="line">     <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger logger = LoggerFactory.getLogger(BusinessException.class);</span><br><span class="line">     <span class="keyword">protected</span> String errorCode;</span><br><span class="line">     <span class="keyword">protected</span> String[] errorMessageArguments;</span><br><span class="line">     <span class="keyword">protected</span> APIResponse apiResponse;</span><br><span class="line">     </span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>


<h4 id="（3）pojo实体类对应的xml"><a href="#（3）pojo实体类对应的xml" class="headerlink" title="（3）pojo实体类对应的xml"></a>（3）pojo实体类对应的xml</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&lt;select id&#x3D;&quot;getUserInfoByCond&quot; resultType&#x3D;&quot;cn.luischen.model.UserDomain&quot;&gt;</span><br><span class="line">    SELECT</span><br><span class="line">    &lt;include refid&#x3D;&quot;BASE_COLUMN&quot;&#x2F;&gt;</span><br><span class="line">    FROM</span><br><span class="line">    &lt;include refid&#x3D;&quot;BASE_TABLE&quot;&#x2F;&gt;</span><br><span class="line">    &lt;where&gt;</span><br><span class="line">        &lt;if test&#x3D;&quot;username !&#x3D; null&quot;&gt;</span><br><span class="line">            AND username &#x3D; #&#123;username, jdbcType&#x3D;VARCHAR&#125;</span><br><span class="line">        &lt;&#x2F;if&gt;</span><br><span class="line">        &lt;if test&#x3D;&quot;password !&#x3D; null&quot;&gt;</span><br><span class="line">            AND password &#x3D; #&#123;password, jdbcType&#x3D;VARCHAR&#125;</span><br><span class="line">        &lt;&#x2F;if&gt;</span><br><span class="line">    &lt;&#x2F;where&gt;</span><br><span class="line">&lt;&#x2F;select&gt;</span><br></pre></td></tr></table></figure>


<p>这里涉及到mybatis，还不太熟悉，持续更新中…</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2021/03/15/php-%E4%BA%91%E4%B8%8A%E5%BC%80%E5%8F%91/" rel="next" title="php 云上开发">
                <i class="fa fa-chevron-left"></i> php 云上开发
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2021/03/16/springboot-%E4%BA%8C%E6%AC%A1%E5%BC%80%E5%8F%91blog%EF%BC%88%E4%BA%8C%EF%BC%89/" rel="prev" title="springboot 二次开发blog（二）">
                springboot 二次开发blog（二） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.png"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
                <a href="/archives">
                  <span class="site-state-item-count">23</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#springboot-%E4%BA%8C%E5%BC%80github-blog%E9%A1%B9%E7%9B%AE%EF%BC%88%E4%B8%80%EF%BC%89"><span class="nav-text">springboot 二开github blog项目（一）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA"><span class="nav-text">一、环境搭建</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E3%80%81%E6%8B%89%E5%8E%BB%E9%A1%B9%E7%9B%AE%E5%88%B0%E6%9C%AC%E5%9C%B0%EF%BC%9A"><span class="nav-text">1、拉去项目到本地：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E3%80%81%E9%85%8D%E7%BD%AE%E6%95%B0%E6%8D%AE%E5%BA%93"><span class="nav-text">2、配置数据库</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E3%80%81%E6%9C%AC%E5%9C%B0%E8%BF%90%E8%A1%8C"><span class="nav-text">3、本地运行</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E6%9E%B6%E6%9E%84%E8%A7%A3%E6%9E%90"><span class="nav-text">二、架构解析</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E3%80%81%E8%BF%90%E8%A1%8C%E9%80%BB%E8%BE%91%EF%BC%9A"><span class="nav-text">1、运行逻辑：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E3%80%81%E7%A4%BA%E4%BE%8B%E4%BB%A3%E7%A0%81%EF%BC%9A"><span class="nav-text">2、示例代码：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%EF%BC%881%EF%BC%89%E6%8E%A7%E5%88%B6%E5%99%A8%E5%B1%82"><span class="nav-text">（1）控制器层</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%EF%BC%882%EF%BC%89service%E5%B1%82"><span class="nav-text">（2）service层</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%EF%BC%883%EF%BC%89pojo%E5%AE%9E%E4%BD%93%E7%B1%BB%E5%AF%B9%E5%BA%94%E7%9A%84xml"><span class="nav-text">（3）pojo实体类对应的xml</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yyc</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
